package com.eagle.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.eagle.EApplication;
import com.eagle.R;
import com.eagle.support.constants.Constants;
import com.eagle.support.utils.ToastUtils;
import com.eagle.view.activity.base.BaseCallActivity;
import com.kinstalk.voip.sdk.EngineSdkCallState;
import com.kinstalk.voip.sdk.EngineSdkUserRole;
import com.kinstalk.voip.sdk.logic.sip.aidl.model.CallInfo;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/10. 电话拨号页面
 */
@EActivity(R.layout.activity_call)
public class CallDialingActivity extends BaseCallActivity {

    @ViewById(R.id.tv_loading)
    protected TextView mTvLoading;

    @ViewById(R.id.tv_name)
    protected TextView mTvName;

    @ViewById(R.id.tv_state)
    protected TextView mTvState;

    @ViewById(R.id.btn_hang_up)
    protected ImageView mIvHangup;

    @ViewById(R.id.btn_answer)
    protected ImageView mIvAnswer;

    @Extra(Constants.CALL_UID)
    protected String mCallNumber;

    @Extra(Constants.ROOM_ID)
    protected String mRoomId;

    @Extra(Constants.CALL_TYPE)
    protected int mCallType;

    @Extra(Constants.CALL_TOKEN)
    protected int mCallToken;

    @Extra(Constants.MEETING_SENDER)
    protected String mMeetingSender;

    private int mLoadingIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFadeTransition();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @AfterViews
    void initView() {
        if (!TextUtils.isEmpty(mCallNumber)) {
            mTvName.setText(mCallNumber);
        }

        if (mCallType == Constants.CALL_TYPE_INCOMING) {
            mIvAnswer.setVisibility(View.VISIBLE);
            handlerLoadingText();
        }

        if (mCallType == Constants.CALL_TYPE_OUT) {
            mCallHelper.startCall(mCallNumber, EApplication.getSharedPreferences().getString(Constants.LOGIN_UID, ""));
            handlerLoadingText();
        }

        if (mCallType == Constants.CALL_TYPE_MEETING_INVITE) {
            mIvAnswer.setVisibility(View.VISIBLE);
            mTvName.setText(mMeetingSender);
            mTvState.setText("Awaiting to join meeting " + mRoomId);
            handlerLoadingText();
        }
    }

    @Click(R.id.btn_hang_up)
    void onHangUp() {
        if (mCallType != Constants.CALL_TYPE_MEETING_INVITE) {
            mCallHelper.hangUpCall();
        }
        finishPage();
    }

    @Click(R.id.btn_answer)
    void onAnswer() {
        if (mCallType == Constants.CALL_TYPE_MEETING_INVITE) {
            mCallHelper.userRole(EngineSdkUserRole.ES_UR_TYPE_SLAVER.swigValue());
            mCallHelper.roomId(mRoomId);
            mCallHelper.answerMeetingInvite(mRoomId);
            MeetingActivity_.intent(this).
                    extra(Constants.CALL_TYPE_MEETING_ANSWER, true).
                    extra(Constants.ROOM_ID, mRoomId).start();
            finishPage();
        } else {
            mCallHelper.answeringCall();
            VideoCallActivity_.intent(this).extra(Constants.CALL_TYPE_CALL_ANSWER, true).start();
            finishPage();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handlerLoadingText() {
        mTvLoading.setText("");
        mHandler.sendEmptyMessageDelayed(0, 1000);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mHandler != null) {
                mTvLoading.append(".");
                mLoadingIndex++;
                if (mLoadingIndex == 4) {
                    mLoadingIndex = 0;
                    mTvLoading.setText("");
                }
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyHandler();
    }

    private void destroyHandler() {
        if (mHandler != null) {
            mHandler.removeMessages(0);
            mHandler = null;
        }
    }

    @Override
    public void onCallStateHandler(CallInfo call, int state) {
        super.onCallStateHandler(call, state);
        switch (EngineSdkCallState.swigToEnum(state)) {
            case ES_STATE_ON_CALL_CALL_ENDED:
                handlerCallEnd();
                break;
            case ES_STATE_ON_CALL_IN_ACTIVE_SESSION:
                sendBroadcast(new Intent(Constants.OUT_CALL_ANSWERED));
                finishPage();
                break;
        }
    }

    private void handlerCallEnd() {
        ToastUtils.showToast(this, "Other user may be busy. Try again later.", R.id.layout_parent);
        destroyHandler();
        new Handler().postDelayed(() -> {
            finishPage();
        }, 2500);
    }
}
